<template>
	<ManagementLayout title="角色管理">
		<div class="action-bar">
			<el-button type="primary" :icon="Plus" @click="openDialog()" class="magic-button-primary">
				创建新角色
			</el-button>
		</div>
		
		<div class="magic-grid">
			<ManagementCard 
				v-for="character in characters" 
				:key="character.id"
				:title="character.name"
				:description="character.description"
				:meta="getCharacterMeta(character)"
			>
				<template #actions>
					<el-button size="small" @click="openDialog(character)">编辑</el-button>
					<el-button size="small" type="danger" @click="handleDelete(character)">删除</el-button>
				</template>
			</ManagementCard>
		</div>
		
		<!-- 创建/编辑对话框 -->
		<el-dialog
				v-model="dialogVisible"
				:title="editingCharacter ? '编辑角色' : '创建角色'"
				width="650px"
		>
			<el-form :model="form" label-width="80px" :rules="formRules" ref="formRef">
				<!-- 基础信息 -->
				<div class="form-section">
					<h4 class="section-title">基础信息</h4>
					<el-form-item label="角色名称" prop="name" required>
						<el-input 
							v-model="form.name" 
							placeholder="请输入角色名称"
							maxlength="50"
							show-word-limit
						/>
					</el-form-item>
					
					<el-form-item label="角色描述" prop="description" required>
						<el-input 
							v-model="form.description" 
							type="textarea" 
							:rows="2" 
							placeholder="简要描述角色的特点和背景"
							maxlength="200"
							show-word-limit
						/>
					</el-form-item>
					
					<el-form-item label="提示模板" prop="prompt_template" required>
						<el-input
							v-model="form.prompt_template"
							type="textarea"
							:rows="4"
							placeholder="定义角色的行为、说话方式和个性特征..."
							maxlength="1000"
							show-word-limit
						/>
						<div class="form-tip">💡 这是角色的核心设定，决定AI如何扮演这个角色</div>
					</el-form-item>
					
					<el-form-item label="可见性">
						<el-radio-group v-model="form.is_public">
							<el-radio :label="true">公开 - 其他用户可以看到和使用</el-radio>
							<el-radio :label="false">私有 - 仅自己可见</el-radio>
						</el-radio-group>
					</el-form-item>
				</div>
				
				<!-- 高级配置 -->
				<div class="form-section">
					<el-button 
						type="text" 
						@click="showAdvanced = !showAdvanced"
						class="section-toggle"
					>
						<i :class="showAdvanced ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i>
						高级配置 {{ showAdvanced ? '(点击收起)' : '(点击展开)' }}
					</el-button>
					
					<div v-show="showAdvanced" class="advanced-config">
						<el-form-item label="语音引擎">
							<el-select v-model="form.tts_engine" style="width: 100%">
								<el-option label="Edge TTS (默认)" value="edge_tts" />
								<el-option label="Index TTS2 (自定义音色)" value="indextts2" />
							</el-select>
						</el-form-item>
						
						<el-form-item label="语音ID">
							<el-input 
								v-model="form.voice_id" 
								placeholder="zh-CN-XiaoxiaoNeural"
							/>
							<div class="form-tip">语音合成的声音标识，使用默认值即可</div>
						</el-form-item>
						
						<el-form-item label="知识库">
							<el-switch 
								v-model="form.use_knowledge_base" 
								active-text="启用知识库增强回答"
								inactive-text="仅使用基础训练数据"
							/>
						</el-form-item>
						
						<el-form-item label="搜索数量" v-if="form.use_knowledge_base">
							<el-input-number 
								v-model="form.knowledge_search_k" 
								:min="1" 
								:max="10"
								controls-position="right"
								style="width: 100%"
							/>
							<div class="form-tip">每次搜索知识库返回的相关文档数量</div>
						</el-form-item>
					</div>
				</div>
			</el-form>
			
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSave" :loading="saving">
						{{ editingCharacter ? '保存更改' : '创建角色' }}
					</el-button>
				</div>
			</template>
		</el-dialog>
	</ManagementLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import * as api from '@/services/api'
import ManagementLayout from './ManagementLayout.vue'
import ManagementCard from './ManagementCard.vue'
import { confirmDelete, handleApiError } from '@/utils/managementUtils'

const characters = ref([])
const dialogVisible = ref(false)
const editingCharacter = ref(null)
const saving = ref(false)
const showAdvanced = ref(false)
const formRef = ref(null)

const form = ref({
	name: '',
	description: '',
	prompt_template: '',
	voice_id: 'zh-CN-XiaoxiaoNeural',
	use_knowledge_base: false,
	knowledge_search_k: 3,
	tts_engine: 'edge_tts',
	is_public: true
})

const formRules = {
	name: [
		{ required: true, message: '请输入角色名称', trigger: 'blur' },
		{ min: 2, max: 50, message: '角色名称长度应在 2-50 个字符', trigger: 'blur' }
	],
	description: [
		{ required: true, message: '请输入角色描述', trigger: 'blur' },
		{ min: 10, max: 200, message: '描述长度应在 10-200 个字符', trigger: 'blur' }
	],
	prompt_template: [
		{ required: true, message: '请输入提示模板', trigger: 'blur' },
		{ min: 20, max: 1000, message: '提示模板长度应在 20-1000 个字符', trigger: 'blur' }
	]
}

// 获取角色元信息
function getCharacterMeta(character) {
	const meta = []
	if (character.tts_engine) meta.push(`TTS: ${character.tts_engine}`)
	if (character.use_knowledge_base) meta.push('知识库')
	if (character.is_public) meta.push('公开')
	return meta
}

onMounted(() => {
	loadCharacters()
})

async function loadCharacters() {
	try {
		characters.value = await api.getMyCharacters()
	} catch (error) {
		ElMessage.error('加载角色列表失败')
	}
}

function openDialog(character = null) {
	editingCharacter.value = character
	showAdvanced.value = false // 重置高级配置展开状态
	
	if (character) {
		// 编辑模式
		form.value = {
			name: character.name,
			description: character.description,
			prompt_template: character.prompt_template || '',
			voice_id: character.voice_id || 'zh-CN-XiaoxiaoNeural',
			use_knowledge_base: character.use_knowledge_base || false,
			knowledge_search_k: character.knowledge_search_k || 3,
			tts_engine: character.tts_engine || 'edge_tts',
			is_public: character.is_public !== false
		}
		// 如果有高级配置项，自动展开高级配置
		if (character.tts_engine !== 'edge_tts' || character.use_knowledge_base || character.voice_id !== 'zh-CN-XiaoxiaoNeural') {
			showAdvanced.value = true
		}
	} else {
		// 创建模式
		form.value = {
			name: '',
			description: '',
			prompt_template: '',
			voice_id: 'zh-CN-XiaoxiaoNeural',
			use_knowledge_base: false,
			knowledge_search_k: 3,
			tts_engine: 'edge_tts',
			is_public: true
		}
	}
	
	dialogVisible.value = true
	// 使用 nextTick 确保 DOM 更新后再清除验证状态
	setTimeout(() => {
		if (formRef.value) {
			formRef.value.clearValidate()
		}
	}, 0)
}

async function handleSave() {
	if (!formRef.value) return
	
	try {
		// 验证表单
		await formRef.value.validate()
	} catch (error) {
		ElMessage.error('请检查并完善表单信息')
		return
	}
	
	saving.value = true
	
	try {
		if (editingCharacter.value) {
			await api.updateCharacter(editingCharacter.value.id, form.value)
			ElMessage.success('角色更新成功')
		} else {
			const character = await api.createCharacter(form.value)
			// 如果创建时设置为私有，则调用切换可见性接口
			if (!form.value.is_public) {
				await api.toggleCharacterVisibility(character.id, false)
			}
			ElMessage.success('角色创建成功')
		}
		
		dialogVisible.value = false
		await loadCharacters()
	} catch (error) {
		console.error('保存失败:', error)
		ElMessage.error(`保存失败: ${error.message || '未知错误'}`)
	} finally {
		saving.value = false
	}
}

async function handleDelete(character) {
	try {
		await confirmDelete(character.name, '角色')
		await api.deleteCharacter(character.id)
		ElMessage.success('删除成功')
		await loadCharacters()
	} catch (error) {
		if (error !== 'cancel') {
			handleApiError(error, '删除失败')
		}
	}
}
</script>

<style scoped>
@import '@/styles/management-common.css';

.action-bar {
	text-align: right;
}

/* 弹窗样式 */
.form-section {
	margin-bottom: 24px;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #303133;
	margin: 0 0 16px 0;
	padding-bottom: 8px;
	border-bottom: 1px solid #EBEEF5;
}

.section-toggle {
	padding: 8px 0;
	color: #409EFF;
	font-weight: 500;
	margin-bottom: 16px;
	display: flex;
	align-items: center;
	gap: 4px;
}

.section-toggle:hover {
	color: #66b1ff;
}

.advanced-config {
	padding-left: 16px;
	border-left: 3px solid #F0F2F5;
	margin-top: 16px;
}

.form-tip {
	font-size: 12px;
	color: #909399;
	margin-top: 4px;
	line-height: 1.4;
}

.dialog-footer {
	text-align: right;
}

/* 自定义单选按钮样式 */
:deep(.el-radio) {
	display: block;
	margin-bottom: 8px;
}

:deep(.el-radio__label) {
	color: #606266;
	font-size: 14px;
}

/* 表单项间距 */
:deep(.el-form-item) {
	margin-bottom: 20px;
}

/* 文本域字数统计样式 */
:deep(.el-input__count) {
	background: rgba(64, 158, 255, 0.1);
	color: #409EFF;
}
</style>